package org.tech4j.captcha.graphical.builder;

import com.google.common.base.Throwables;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.function.TriFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tech4j.captcha.api.model.CaptchaResponse;
import org.tech4j.captcha.graphical.config.CaptchaGraphicalConfig;
import org.tech4j.captcha.graphical.model.CheckCaptchaEntity;
import org.tech4j.captcha.graphical.model.GraphicalCaptchaEntity;
import org.tech4j.captcha.graphical.model.GraphicalResult;
import org.tech4j.captcha.graphical.model.PointValue;
import org.tech4j.captcha.graphical.model.VerifyCaptchaEntity;
import org.tech4j.captcha.graphical.utils.ImageUtils;
import org.tech4j.common.spi.Join;
import org.tech4j.common.utils.CryptoUtils;
import org.tech4j.common.utils.JsonUtils;
import org.tech4j.common.utils.RandomUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Objects;
import java.util.Random;
import java.util.UUID;
import java.util.function.Function;

import static org.tech4j.captcha.graphical.config.CaptchaGraphicalConfig.HAN_ZI_SIZE;
import static org.tech4j.captcha.graphical.config.CaptchaGraphicalConfig.HAN_ZI_SIZE_HALF;
import static org.tech4j.captcha.graphical.config.CaptchaGraphicalConfig.IMAGE_TYPE_PNG;

/**
 * @program: tech4j
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/5 09:16
 **/
@Join
public class BlockPuzzleGraphicalCaptchaEntityBuilder implements GraphicalCaptchaEntityBuilder {
    private static final Logger log = LoggerFactory.getLogger(BlockPuzzleGraphicalCaptchaEntityBuilder.class);
    private final Function<CaptchaGraphicalConfig, GraphicalResult> function = (config) -> {
        //原生图片
        BufferedImage originalImage = ImageUtils.getOriginal();
        if (null == originalImage) {
            log.error("滑动底图未初始化成功，请检查路径");
            return GraphicalResult.ofFailed("captcha_basemap_null", "底图未初始化成功，请检查路径");
        }
        //设置水印
        Graphics backgroundGraphics = originalImage.getGraphics();
        CaptchaGraphicalConfig.WaterMarkConfig waterMarkConfig = config.getWaterMarkConfig();
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();
        backgroundGraphics.setFont(waterMarkConfig.getWaterMarkFont());
        backgroundGraphics.setColor(Color.white);
        backgroundGraphics.drawString(waterMarkConfig.getWaterMark(), width - getEnOrChLength(waterMarkConfig.getWaterMark()), height - (HAN_ZI_SIZE / 2) + 7);

        //抠图图片
        String jigsawImageBase64 = ImageUtils.getslidingBlock();
        BufferedImage jigsawImage = ImageUtils.getBase64StrToImage(jigsawImageBase64);
        if (null == jigsawImage) {
            log.error("滑动底图未初始化成功，请检查路径");
            return GraphicalResult.ofFailed("captcha_basemap_null", "底图未初始化成功，请检查路径");
        }

        return getGraphicalResult(config, originalImage, jigsawImage, jigsawImageBase64);
    };

    private final TriFunction<CaptchaGraphicalConfig, CheckCaptchaEntity, String, CaptchaResponse> captchaCheck = (config, checkCaptchaEntity, pointValueJson) -> {
        PointValue pointValue = JsonUtils.parse(pointValueJson, PointValue.class);
        if (Objects.isNull(pointValue)) {
            log.error("BlockPuzzleGraphicalCaptchaEntityBuilder captchaCheckFunction error, reason is pointValue null");
            return CaptchaResponse.ofFailed("point_parse_error", "验证码坐标解析错误");
        }
        String secretKey = pointValue.getSecretKey();
        String decryptPointJson = null;
        try {
            decryptPointJson = CryptoUtils.decryptWithAES(checkCaptchaEntity.getPointValue(), secretKey);
        } catch (Exception e) {
            return CaptchaResponse.ofFailed("crypto_decrypt_failed", Throwables.getStackTraceAsString(e));
        }
        if (StringUtils.isBlank(decryptPointJson)) {
            log.error("BlockPuzzleGraphicalCaptchaEntityBuilder captchaCheckFunction error, reason is pointValue decrypt failed");
            return CaptchaResponse.ofFailed("point_parse_error", "验证码坐标解析错误");
        }
        CaptchaGraphicalConfig.CaptchaConfig captchaConfig = config.getCaptchaConfig();
        PointValue pointDecrypt = JsonUtils.parse(decryptPointJson, PointValue.class);
        if (Objects.isNull(pointDecrypt)) {
            log.error("BlockPuzzleGraphicalCaptchaEntityBuilder captchaCheckFunction error, reason is pointDecrypt null");
            return CaptchaResponse.ofFailed("point_parse_error", "验证码坐标解析错误");
        }
        if (pointValue.getX() - captchaConfig.getSlipOffset() > pointDecrypt.getX()
                || pointDecrypt.getX() > pointValue.getX() + captchaConfig.getSlipOffset()
                || pointValue.getY() != pointDecrypt.getY()) {
            // 失败次数记录

            return CaptchaResponse.ofFailed("captcha_coordinate_error", "验证失败");
        }
        String value = checkCaptchaEntity.getKey().concat("---").concat(decryptPointJson);
        try {
            String data = CryptoUtils.encryptWithAES(value, secretKey);
            return CaptchaResponse.ofSuccess(data);
        } catch (Exception e) {
            return CaptchaResponse.ofFailed("crypto_encrypt_failed", Throwables.getStackTraceAsString(e));
        }
    };

    @Override
    public GraphicalCaptchaEntity buildCaptchaEntity(String key, String storeType, Long expireAt) {
        GraphicalCaptchaEntity graphicalCaptchaEntity = new GraphicalCaptchaEntity();
        graphicalCaptchaEntity.setKey(key);
        graphicalCaptchaEntity.setExpireAt(expireAt);
        graphicalCaptchaEntity.setStoreType(storeType);
        graphicalCaptchaEntity.setResult(function);
        return graphicalCaptchaEntity;
    }

    @Override
    public CheckCaptchaEntity buildCheckCaptchaEntity(String key, String storeType, String pointValue, Long expireAt) {
        CheckCaptchaEntity checkCaptchaEntity = new CheckCaptchaEntity();
        checkCaptchaEntity.setKey(key);
        checkCaptchaEntity.setStoreType(storeType);
        checkCaptchaEntity.setExpireAt(expireAt);
        checkCaptchaEntity.setCaptchaCheck(captchaCheck);
        return checkCaptchaEntity;
    }

    @Override
    public VerifyCaptchaEntity buildVerifyCaptchaEntity(String key, String storeType) {
        VerifyCaptchaEntity verifyCaptchaEntity = new VerifyCaptchaEntity();
        verifyCaptchaEntity.setKey(key);
        verifyCaptchaEntity.setStoreType(storeType);
        return verifyCaptchaEntity;
    }

    private static GraphicalResult getGraphicalResult(CaptchaGraphicalConfig config, BufferedImage originalImage, BufferedImage jigsawImage, String jigsawImageBase64) {
        try {
            int originalWidth = originalImage.getWidth();
            int originalHeight = originalImage.getHeight();
            int jigsawWidth = jigsawImage.getWidth();
            int jigsawHeight = jigsawImage.getHeight();
            PointValue pointValue = generateJigsawPoint(originalWidth, originalHeight, jigsawWidth, jigsawHeight, config);
            int x = pointValue.getX();
            //生成新的拼图图像
            BufferedImage newJigsawImage = new BufferedImage(jigsawWidth, jigsawHeight, jigsawImage.getType());
            Graphics2D graphics = newJigsawImage.createGraphics();
            int bold = 5;
            //如果需要生成RGB格式，需要做如下配置,Transparency 设置透明
            newJigsawImage = graphics.getDeviceConfiguration().createCompatibleImage(jigsawWidth, jigsawHeight, Transparency.TRANSLUCENT);
            // 新建的图像根据模板颜色赋值,源图生成遮罩
            cutByTemplate(originalImage, jigsawImage, newJigsawImage, x, 0);
            CaptchaGraphicalConfig.CaptchaConfig captchaConfig = config.getCaptchaConfig();
            if (captchaConfig.getInterferenceOptions() > 0) {
                int position = 0;
                if (originalWidth - x - 5 > jigsawWidth * 2) {
                    //在原扣图右边插入干扰图
                    position = RandomUtils.randomInt(x + jigsawWidth + 5, originalWidth - jigsawWidth);
                } else {
                    //在原扣图左边插入干扰图
                    position =  RandomUtils.randomInt(100, x - jigsawWidth - 5);
                }
                while (true) {
                    String s = ImageUtils.getslidingBlock();
                    if (StringUtils.equals(jigsawImageBase64, s)) {
                        interferenceByTemplate(originalImage, Objects.requireNonNull(ImageUtils.getBase64StrToImage(s)), position, 0);
                        break;
                    }
                }
            }
            if (captchaConfig.getInterferenceOptions() > 1) {
                while (true) {
                    String s = ImageUtils.getslidingBlock();
                    if (StringUtils.equals(jigsawImageBase64, s)) {
                        Integer randomInt =  RandomUtils.randomInt(jigsawWidth, 100 - jigsawWidth);
                        interferenceByTemplate(originalImage, Objects.requireNonNull(ImageUtils.getBase64StrToImage(s)),
                                randomInt, 0);
                        break;
                    }
                }
            }


            // 设置“抗锯齿”的属性
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            graphics.setStroke(new BasicStroke(bold, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
            graphics.drawImage(newJigsawImage, 0, 0, null);
            graphics.dispose();

            ByteArrayOutputStream os = new ByteArrayOutputStream();//新建流。
            ImageIO.write(newJigsawImage, IMAGE_TYPE_PNG, os);//利用ImageIO类提供的write方法，将bi以png图片的数据模式写入流。
            byte[] jigsawImages = os.toByteArray();

            ByteArrayOutputStream oriImagesOs = new ByteArrayOutputStream();//新建流。
            ImageIO.write(originalImage, IMAGE_TYPE_PNG, oriImagesOs);//利用ImageIO类提供的write方法，将bi以jpg图片的数据模式写入流。
            byte[] oriCopyImages = oriImagesOs.toByteArray();
            Base64.Encoder encoder = Base64.getEncoder();
            GraphicalResult result = new GraphicalResult();
            result.setOriginalImageBase64(encoder.encodeToString(oriCopyImages).replaceAll("\r|\n", ""));
            //point信息不传到前端，只做后端check校验
            result.setPointValueJson(JsonUtils.toJsonString(pointValue));
            result.setJigsawImageBase64(encoder.encodeToString(jigsawImages).replaceAll("\r|\n", ""));
            result.setToken(UUID.randomUUID().toString());
            result.setSecretKey(pointValue.getSecretKey());
            return result;
        } catch (Exception e) {
            log.error("BlockPuzzleGraphicalCaptchaEntityBuilder apply function error", e);
            return null;
        }
    }

    /**
     * 随机生成拼图坐标
     *
     * @param originalWidth
     * @param originalHeight
     * @param jigsawWidth
     * @param jigsawHeight
     * @return
     */
    private static PointValue generateJigsawPoint(int originalWidth, int originalHeight, int jigsawWidth, int jigsawHeight, CaptchaGraphicalConfig config) {
        Random random = new Random();
        int widthDifference = originalWidth - jigsawWidth;
        int heightDifference = originalHeight - jigsawHeight;
        int x, y = 0;
        if (widthDifference <= 0) {
            x = 5;
        } else {
            x = random.nextInt(originalWidth - jigsawWidth - 100) + 100;
        }
        if (heightDifference <= 0) {
            y = 5;
        } else {
            y = random.nextInt(originalHeight - jigsawHeight) + 5;
        }
        String key = null;
        if (config.getAseOpen()) {
            key = CryptoUtils.getKey16();
        }
        return new PointValue(x, y, key);
    }

    protected static int getEnOrChLength(String s) {
        int enCount = 0;
        int chCount = 0;
        for (int i = 0; i < s.length(); i++) {
            int length = String.valueOf(s.charAt(i)).getBytes(StandardCharsets.UTF_8).length;
            if (length > 1) {
                chCount++;
            } else {
                enCount++;
            }
        }
        int chOffset = HAN_ZI_SIZE_HALF * chCount + 5;
        int enOffset = enCount * 8;
        return chOffset + enOffset;
    }

    /**
     * @param oriImage      原图
     * @param templateImage 模板图
     * @param newImage      新抠出的小图
     * @param x             随机扣取坐标X
     * @param y             随机扣取坐标y
     * @throws Exception
     */
    private static void cutByTemplate(BufferedImage oriImage, BufferedImage templateImage, BufferedImage newImage, int x, int y) {
        //临时数组遍历用于高斯模糊存周边像素值
        int[][] martrix = new int[3][3];
        int[] values = new int[9];

        int xLength = templateImage.getWidth();
        int yLength = templateImage.getHeight();
        // 模板图像宽度
        for (int i = 0; i < xLength; i++) {
            // 模板图片高度
            for (int j = 0; j < yLength; j++) {
                // 如果模板图像当前像素点不是透明色 copy源文件信息到目标图片中
                int rgb = templateImage.getRGB(i, j);
                if (rgb < 0) {
                    newImage.setRGB(i, j, oriImage.getRGB(x + i, y + j));

                    //抠图区域高斯模糊
                    readPixel(oriImage, x + i, y + j, values);
                    fillMatrix(martrix, values);
                    oriImage.setRGB(x + i, y + j, avgMatrix(martrix));
                }

                //防止数组越界判断
                if (i == (xLength - 1) || j == (yLength - 1)) {
                    continue;
                }
                int rightRgb = templateImage.getRGB(i + 1, j);
                int downRgb = templateImage.getRGB(i, j + 1);
                //描边处理，,取带像素和无像素的界点，判断该点是不是临界轮廓点,如果是设置该坐标像素是白色
                if ((rgb >= 0 && rightRgb < 0) || (rgb < 0 && rightRgb >= 0) || (rgb >= 0 && downRgb < 0) || (rgb < 0 && downRgb >= 0)) {
                    newImage.setRGB(i, j, Color.white.getRGB());
                    oriImage.setRGB(x + i, y + j, Color.white.getRGB());
                }
            }
        }

    }

    /**
     * 干扰抠图处理
     *
     * @param oriImage      原图
     * @param templateImage 模板图
     * @param x             随机扣取坐标X
     * @param y             随机扣取坐标y
     * @throws Exception
     */
    private static void interferenceByTemplate(BufferedImage oriImage, BufferedImage templateImage, int x, int y) {
        //临时数组遍历用于高斯模糊存周边像素值
        int[][] martrix = new int[3][3];
        int[] values = new int[9];

        int xLength = templateImage.getWidth();
        int yLength = templateImage.getHeight();
        // 模板图像宽度
        for (int i = 0; i < xLength; i++) {
            // 模板图片高度
            for (int j = 0; j < yLength; j++) {
                // 如果模板图像当前像素点不是透明色 copy源文件信息到目标图片中
                int rgb = templateImage.getRGB(i, j);
                if (rgb < 0) {
                    //抠图区域高斯模糊
                    readPixel(oriImage, x + i, y + j, values);
                    fillMatrix(martrix, values);
                    oriImage.setRGB(x + i, y + j, avgMatrix(martrix));
                }
                //防止数组越界判断
                if (i == (xLength - 1) || j == (yLength - 1)) {
                    continue;
                }
                int rightRgb = templateImage.getRGB(i + 1, j);
                int downRgb = templateImage.getRGB(i, j + 1);
                //描边处理，,取带像素和无像素的界点，判断该点是不是临界轮廓点,如果是设置该坐标像素是白色
                if ((rgb >= 0 && rightRgb < 0) || (rgb < 0 && rightRgb >= 0) || (rgb >= 0 && downRgb < 0) || (rgb < 0 && downRgb >= 0)) {
                    oriImage.setRGB(x + i, y + j, Color.white.getRGB());
                }
            }
        }

    }

    private static void readPixel(BufferedImage img, int x, int y, int[] pixels) {
        int xStart = x - 1;
        int yStart = y - 1;
        int current = 0;
        for (int i = xStart; i < 3 + xStart; i++) {
            for (int j = yStart; j < 3 + yStart; j++) {
                int tx = i;
                if (tx < 0) {
                    tx = -tx;

                } else if (tx >= img.getWidth()) {
                    tx = x;
                }
                int ty = j;
                if (ty < 0) {
                    ty = -ty;
                } else if (ty >= img.getHeight()) {
                    ty = y;
                }
                pixels[current++] = img.getRGB(tx, ty);

            }
        }
    }

    private static void fillMatrix(int[][] matrix, int[] values) {
        int filled = 0;
        for (int i = 0; i < matrix.length; i++) {
            int[] x = matrix[i];
            for (int j = 0; j < x.length; j++) {
                x[j] = values[filled++];
            }
        }
    }

    private static int avgMatrix(int[][] matrix) {
        int r = 0;
        int g = 0;
        int b = 0;
        for (int i = 0; i < matrix.length; i++) {
            int[] x = matrix[i];
            for (int j = 0; j < x.length; j++) {
                if (j == 1) {
                    continue;
                }
                Color c = new Color(x[j]);
                r += c.getRed();
                g += c.getGreen();
                b += c.getBlue();
            }
        }
        return new Color(r / 8, g / 8, b / 8).getRGB();
    }

}
